package cn.anecansaitin.whimsy.common.network;

import cn.anecansaitin.whimsy.Whimsy;
import cn.anecansaitin.whimsy.common.capabilities.battle.BattleMode;
import cn.anecansaitin.whimsy.common.capabilities.battle.IBattleMode;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.neoforged.neoforge.network.handling.PlayPayloadContext;

public record BattleModeUpdatePack(boolean isInMode) implements CustomPacketPayload {
    public static final ResourceLocation ID = Whimsy.resource("battle_mode_update_pack");

    public BattleModeUpdatePack(FriendlyByteBuf buffer) {
        this(buffer.readBoolean());
    }

    public BattleModeUpdatePack(BattleMode battleMode) {
        this(battleMode.isInMode());
    }

    @Override
    public void write(FriendlyByteBuf buffer) {
        buffer.writeBoolean(isInMode);
    }

    @Override
    public ResourceLocation id() {
        return ID;
    }

    public static void clientHandler(BattleModeUpdatePack pack, PlayPayloadContext context) {
        context.workHandler().submitAsync(() -> context.player().ifPresent(player -> {
            IBattleMode battleMode = player.getCapability(BattleMode.BATTLE_MODE);

            if (battleMode == null) {
                return;
            }

            battleMode.setMode(pack.isInMode);
        }));
    }
}
